<template>
  <view class="recharge-page">
    <view class="header">
      <text class="header-title"></text>
      <u-icon label="历史记录" size="46" @click="showRechargeHistory" shape="circle" name="file-text"></u-icon>
    </view>
    <view class="package-selection">
      <text class="section-title">选择充值套餐</text>
      <view class="packages">
        <view
            v-for="(pkg, index) in packages"
            :key="index"
            class="package-item"
            :class="{ selected: selectedPackage === pkg }"
            @click="selectPackage(pkg)"
        >
          <text>{{ pkg.money }} 元</text>
          <text v-if="pkg.gift_money > 0" class="gift-money">+{{ pkg.gift_money }} 赠送</text>
        </view>
      </view>
    </view>
    <view class="custom-amount">
      <text class="section-title">自定义充值金额</text>
      <u-input
          class="input-monty"
          placeholder="请输入充值金额"
          type="number"
          v-model="customAmount"
          clearable
          border
      ></u-input>
    </view>
    <view class="total-amount">
      <text class="label">总计:</text>
      <text class="amount">{{ totalAmount }} 元</text>
    </view>
    <u-button type="primary" @click="confirmRecharge" style="margin-top: 20px;">确认充值</u-button>
    <u-modal v-model="showModal" :title="modalTitle" :content="modalContent" :show-cancel="false"></u-modal>
    <u-toast ref="uToast"></u-toast>
    <c_payment from="recharge" ref="paymentSelector" @payment-selected="onPaymentMethodChange"
               @confirm="confirmPay"></c_payment>
  </view>
</template>

<script>
import {ready, pay} from "@/pages/packageA/user/recharge/recharge_api";
import c_payment from "@/components/payment/c_payment.vue";

export default {
  name: "Recharge",
  components: {
    c_payment
  },
  data() {
    return {
      packages: [],
      selectedPackage: null,
      customAmount: '',
      showModal: false,
      modalTitle: '',
      modalContent: ''
    };
  },
  computed: {
    totalAmount() {
      if (this.selectedPackage) {
        return parseFloat(this.selectedPackage.money) + parseFloat(this.selectedPackage.gift_money);
      }
      if (this.customAmount) {
        return parseFloat(this.customAmount);
      }
      return 0;
    }
  },
  watch: {
    customAmount() {
      this.selectedPackage = null;
    }
  },
  onLoad() {
    ready().then(res => {
      //console.log(res);
      if (res.code === 0) {
        this.packages = res.data.packages;
      }
    });
  },
  methods: {
    selectPackage(pkg) {
      this.selectedPackage = pkg;
      this.customAmount = '';
    },
    confirmRecharge() {
      if (!this.totalAmount || this.totalAmount <= 0) {
        this.$refs.uToast.show({
          title: '请输入有效的充值金额',
          type: 'warning'
        });
        return;
      }
      this.paymentSelectorOpen();
    },
    // 显示充值记录
    showRechargeHistory() {
      uni.navigateTo({
        url: '/pages/packageA/user/recharge/history'
      });
    },
    paymentSelectorOpen() {
      this.$refs.paymentSelector.openPopup();
    },
    onPaymentMethodChange(e) {
      console.log(e)
    },
    confirmPay(e) {
      console.log('confirmPay', e)
      const pay_way = e.value
      if (!e.value) {
        uni.showToast({
          title: '请选择支付方式',
          icon: 'none'
        })
        return;
      }

      let that = this;
      let amount = this.selectedPackage ? this.selectedPackage.money : this.customAmount;
      const package_id = this.selectedPackage ? this.selectedPackage.id : '';
      pay({
        money: amount,
        package_id: package_id,
        pay_type: pay_way,
        pay_way: pay_way,
      }).then(res => {
        if (res.code !== 0) {
          this.$refs.uToast.show({
            title: res.msg,
            type: 'warning'
          });
          return;
        }
        console.log(res)
        if (pay_way == 1) {
          let param = res.data.param;
          // 发起微信支付(小程序)
          uni.requestPayment({
            timeStamp: param.timeStamp,
            nonceStr: param.nonceStr,
            package: 'prepay_id=' + param.prepay_id,
            signType: 'MD5',
            paySign: param.paySign,
            success: function (res) {
              that.getOrderDetail(that.order_sn);
            },
            fail: () => {
              that.show_msg('支付失败')
            }
          });
        } else if (pay_way == 2) {
          //支付宝
          //#ifdef H5
          console.log(res.data.url)
          uni.navigateTo({
            url: '/pages/packageA/h5/web?bsfrom=recharge&order_sn=' + res.data.order_sn + '&url=' + res.data.url,
            success: () => {
            },
            fail: (err) => {
              console.log(err)
            }
          })
          return;
          //#endif

          uni.requestPayment({
            provider: 'alipay',
            orderInfo: res.data.params,
            success: function (res) {
               uni.navigateBack()
            },
            fail: function (res) {
              that.show_msg('支付失败')
            }
          });
        }else if (pay_way == 3) {
          that.$u.toast(res.msg)
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/packageA/user/center'
            })
          },1000)

        }
      })

    },
  }
};
</script>

<style scoped>
.recharge-page {
  padding: 20px;
  background-color: #f9f9f9;
  height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  font-size: 24px;
  font-weight: bold;
}

.package-selection {
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.packages {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.package-item {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-align: center;
  cursor: pointer;
}

.package-item.selected {
  border-color: #FF9900;
  background-color: #FFF9F0;
}

.gift-money {
  color: #FF9900;
  font-size: 12px;
}

.custom-amount {
  margin-top: 20rpx;
  margin-bottom: 20px;
}

.input-monty {
  margin-top: 20rpx;
}

.total-amount {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  margin-bottom: 20px;
}

.label {
  font-weight: bold;
}

.amount {
  color: #FF9900;
}
</style>



